//
// Created on 2024/2/29.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#include "OHAudioUtils.h"

constexpr int32_t WAIT_INTERVAL = 1000;

FILE *g_file = nullptr;
bool g_readEnd = false;
// 音频采样率
int32_t g_samplingRate = 48000;
// 音频声道数
int32_t g_channelCount = 2;
// 音频场景：0代表正常场景，1代表低时延场景
int32_t g_latencyMode = 0;
// 音频采样格式
int32_t g_sampleFormat = 1;


static int32_t AudioRendererOnWriteData(OH_AudioRenderer *capturer, void *userData, void *buffer, int32_t bufferLen) {
    size_t readCount = fread(buffer, bufferLen, 1, g_file);
    if (!readCount) {
        if (ferror(g_file)) {
            printf("Error reading myfile");
        } else if (feof(g_file)) {
            printf("EOF found");
            g_readEnd = true;
        }
    }
    return 0;
}

void OHAudioUtils::play(const char *audioPath){

    g_file = fopen(audioPath, "rb");

    if (g_file == nullptr) {
        return;
    }

    OH_AudioStream_Result ret;

    // 1. 创建构造器
    OH_AudioStreamBuilder *builder;
    OH_AudioStream_Type type = AUDIOSTREAM_TYPE_RENDERER;
    ret = OH_AudioStreamBuilder_Create(&builder, type);

    // 2. 设置音频流所需要的参数
    OH_AudioStreamBuilder_SetSamplingRate(builder, g_samplingRate);
    OH_AudioStreamBuilder_SetChannelCount(builder, g_channelCount);
    OH_AudioStreamBuilder_SetLatencyMode(builder, (OH_AudioStream_LatencyMode)g_latencyMode);
    OH_AudioStreamBuilder_SetSampleFormat(builder, (OH_AudioStream_SampleFormat)g_sampleFormat);

    // 设置回调函数, 播放的音频数据要通过回调接口写入
    OH_AudioRenderer_Callbacks callbacks;
    callbacks.OH_AudioRenderer_OnWriteData = AudioRendererOnWriteData;
    ret = OH_AudioStreamBuilder_SetRendererCallback(builder, callbacks, nullptr);

    // 3. 构造播放音频流
    OH_AudioRenderer *audioRenderer;
    ret = OH_AudioStreamBuilder_GenerateRenderer(builder, &audioRenderer);

    // 4. 开始播放
    ret = OH_AudioRenderer_Start(audioRenderer);

    int timer = 0;
    while (!g_readEnd) {
        std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_INTERVAL));
        int64_t frames;
        OH_AudioRenderer_GetFramesWritten(audioRenderer, &frames);
        printf("Wait for the audio to finish playing.(..%d s) frames:%ld\n", ++timer, frames);
        int64_t framePosition;
        int64_t timestamp;
        OH_AudioRenderer_GetTimestamp(audioRenderer, CLOCK_MONOTONIC, &framePosition, &timestamp);
        printf("framePosition %ld timestamp:%ld\n", framePosition, timestamp);
    }
    // 5. 停止播放
    ret = OH_AudioRenderer_Stop(audioRenderer);

    // 释放播放实例
    ret = OH_AudioRenderer_Release(audioRenderer);

    // 6. 释放构造器
    ret = OH_AudioStreamBuilder_Destroy(builder);

    // 播放完成后关闭文件资源
    fclose(g_file);
    g_file = nullptr;
}
